package interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;




public class AuthorityInterceptor extends AbstractInterceptor{
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		//获取根目录所对应的绝对路径
		String currentURL = request.getRequestURI();
		//截取到当前文件名用于比较
		String targetURL = currentURL.substring(currentURL.lastIndexOf("/"),currentURL.length());
		//System.out.println(targetURL);
		//如果session不为空就返回该session，如果为空就返回null
		HttpSession session = request.getSession(false);
		if(!"/login.html".equals(targetURL)){
			//判断当前页面是否是重定向后的登陆页面页面，如果是就不做session的判断，防止死循环
			if(session==null||session.getAttribute("account")==null){
				//如果session为空表示用户没有登陆就重定向到login.html页面
				//System.out.println("request.getContextPath()=" + request.getContextPath());
				//重置cookie
				Cookie cookie=new Cookie("account",null);
//				cookie.setMaxAge(0);
				response.addCookie(cookie);
				response.sendRedirect(request.getContextPath()+"/login.html");
				return null;
			}
		}
		//继续向下执行
		String result = invocation.invoke();
		return result;
	}
}
